package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.common.schedule.dtos.Task;
import com.heima.model.common.schedule.pojos.Taskinfo;
import com.heima.model.common.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private RedisCacheService redisCacheService;


    @Autowired(required = false)
    private ThreadPoolTaskExecutor threaPool;


    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    /**
     * 添加任务list中
     *
     * @param task 任务对象
     * @return
     */
    @Override
    public Long addTask(Task task) {
        //使用多线程的方式
        Future<Long> future = threadPoolTaskExecutor.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                //1.添加任务到数据库中
                boolean success = addTaskToDb(task);

                if (success) {
                    //2.添加任务到redis
                    addTaskToCache(task);
                }

                return task.getTaskId();
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务，更新日志
        Task task = updateDb(taskId,ScheduleConstants.EXECUTED);

        //删除redis的数据
        if(task != null){
            removeTaskFromCache(task);
            flag = true;
        }



        return false;
    }

    /**
     * 按照类型和优先级来拉取任务
     *消费任务，一定是从redis中list队列中拉取任务，不涉及zset队列
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        //使用多线程的方式
        Future<Task> future = threadPoolTaskExecutor.submit(new Callable<Task>() {
            @Override
            public Task call() throws Exception {
                String keySuffix = type + "_" + priority;
                //1.从redis的list中取出数据并删除
                String taskStr = redisCacheService.lRightPop(ScheduleConstants.TOPIC + keySuffix);
                if (taskStr != null) {
                    //3.把获取到taskStr转化成对象类型，从而获取taskId参数
                    Task task = JSON.parseObject(taskStr, Task.class);
                    //2.修改数据库的表，删除任务表以及修改任务日志表的状态以及version
                    taskinfoMapper.deleteById(task.getTaskId());
                    TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                    if (taskinfoLogs != null) {
                        taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);//表示消费状态
                        //按照正常来说我们还要对version更新,此时不需要，因为mp已经集成version乐观锁
                        //taskinfoLogs.setVersion();
                        taskinfoLogsMapper.updateById(taskinfoLogs);
                    }
                    //4.返回数据
                    return task;
                }
                return null;
            }
        });

        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    /**
     * 定时刷新同步数据
     * 添加一个定时任务方法
     */
    @Scheduled(cron ="0 */1 * * * ?") //每分钟执行一次
    // @Scheduled(cron = "*/1 * * * * ?") //换成每秒中执行一次，方便测试
    public void refresh() {
        threaPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");
                //暂时把锁去掉，避免影响测试
                // redisCacheService.tryLock("FUTURE_TASK_SYNC",1000*30);
                // 获取所有未来数据集合的key值
                Set<String> futureKeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
                for (String futureKey : futureKeys) { // future_250_250
                    //获取该组key下当前需要消费的任务数据
                    Set<String> tasks = redisCacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    if (!tasks.isEmpty()) {
                        //获取toipcKey
                        String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                        //将这些任务数据添加到消费者队列中
                        redisCacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                        System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                    }
                }
            }
        });

    }

    /**
     * 数据库同步到redis
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        clearCache();
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务
        List<Taskinfo> allTasks = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime,calendar.getTime()));
        if(allTasks != null && allTasks.size() > 0){
            for (Taskinfo taskinfo : allTasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    private void clearCache(){
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = redisCacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        redisCacheService.delete(futurekeys);
        redisCacheService.delete(topickeys);
    }

    /**
     * 删除redis中的任务数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        String key = task.getTaskType()+"_"+task.getPriority();

        if(task.getExecuteTime()<=System.currentTimeMillis()){
            redisCacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            redisCacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            log.error("task cancel exception taskid={}",taskId);
        }

        return task;

    }



    /**
     * 把任务添加到redis中
     *
     * @param task
     */
    private void addTaskToCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        //2.1 如果执行时间小于当前时间，则存入list中
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            redisCacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }
        //2.2如果执行时间大于当前时间，小于预设时间(当前时间+5分钟)，则存入zset中
            //获取预设时间=当前时间+5分钟
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        //获取当前时间的5分钟之后的毫秒值
        long fiveTime = calendar.getTimeInMillis();
        if(task.getExecuteTime()>System.currentTimeMillis() && task.getExecuteTime()<=fiveTime){
            redisCacheService.zAdd(ScheduleConstants.FUTURE+key, JSON.toJSONString(task),task.getExecuteTime());
        }


    }



    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flag = false;

        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }
}